package com.kwd.news.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.kwd.news.controller.MobileController;
import com.kwd.news.dao.GlobalConfigDao;
import com.kwd.news.dao.LmCmsAreasDao;
import com.kwd.news.dao.LmCmsMobileDao;
import com.kwd.news.model.GlobalConfig;
import com.kwd.news.model.LmCmsMobile;
import com.kwd.news.model.LmCmsPhone;
import com.kwd.news.po.Mobilehd;
import com.kwd.news.service.LmCmsPhoneService;
import com.kwd.news.utils.MobileUtil;
import com.meirengu.common.RedisClient;
import com.meirengu.common.StatusCode;
import com.meirengu.model.Result;
import com.meirengu.service.impl.BaseServiceImpl;
import com.meirengu.utils.JacksonUtil;
import com.meirengu.utils.NumberUtil;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * LmCmsPhone服务实现层
 *
 * @author Mao
 * @create Wed May 16 16:32:31 CST 2018
 */
@Service
public class LmCmsPhoneServiceImpl extends BaseServiceImpl<LmCmsPhone> implements LmCmsPhoneService {

    Logger logger = LoggerFactory.getLogger(LmCmsPhoneServiceImpl.class);

    @Autowired
    private RedisClient redisClient;

    @Autowired
    private LmCmsAreasDao lmCmsAreasDao;

    @Autowired
    private GlobalConfigDao globalConfigDao;

    @Autowired
    private LmCmsMobileDao lmCmsMobileDao;


    /**
     * 检测城市是否存在，并且匹配code
     */
    @Override
    @Async
    public void cityExist(int idBegin, int idEnd) {
        Map<String, Object> param = new HashMap<>();
        param.put("idBegin", idBegin);
        param.put("idEnd", idEnd);
        try {
            List<Map<String, Object>> phoneList = getList(param);
            if (phoneList != null && phoneList.size() > 0) {
                for (Map<String, Object> map : phoneList) {
                    if (map != null) {
                        //先检查省份，再检查城市
                        String province = (String) map.get("province");
                        String phone = (String) map.get("phone");

                        Map<String, Object> provinceParam = new HashMap<>();
                        provinceParam.put("shortName", province);
                        provinceParam.put("levelType", 1);
                        List<Map<String, Object>> provinceList = lmCmsAreasDao.getByPage(provinceParam);
                        if (provinceList != null && provinceList.size() > 0) {
                            if (provinceList.size() == 1) {
                                Map<String, Object> provinceArea = provinceList.get(0);

                                String city = (String) map.get("city");
                                String cityCode = (String) map.get("areaCode");

                                Map<String, Object> cityParam = new HashMap<>();
                                cityParam.put("shortName", city);
                                cityParam.put("levelType", 2);
                                cityParam.put("parentCode", provinceArea.get("code"));
                                List<Map<String, Object>> cityList = lmCmsAreasDao.getByPage(cityParam);
                                if (cityList != null && cityList.size() > 0) {
                                    if (cityList.size() == 1) {
                                        Map<String, Object> lmCmsArea = cityList.get(0);
                                        if (!cityCode.equals(lmCmsArea.get("code").toString())) {
                                            addErrorLog(city, "code错误", phone);
                                        }
                                    } else {
                                        addErrorLog(city, "多个城市", phone);
                                    }
                                } else {
                                    Map<String, Object> areaParam = new HashMap<>();
                                    areaParam.put("shortName", city);
                                    areaParam.put("levelType", 3);
                                    List<Map<String, Object>> areaList = lmCmsAreasDao.getByPage(areaParam);
                                    if (areaList != null && areaList.size() > 0) {
                                        if (areaList.size() == 1) {
                                            Map<String, Object> lmCmsArea = areaList.get(0);
                                            if (!cityCode.equals(lmCmsArea.get("code").toString())) {
                                                addErrorLog(city, "3级code错误", phone);
                                            } else {
                                                addErrorLog(city, "3级", phone);
                                            }
                                        } else {
                                            addErrorLog(city, "3级多城市", phone);
                                        }
                                    } else {
                                        addErrorLog(city, "无", phone);
                                    }

                                }
                            } else {
                                addErrorLog(province + "省", "多个省", phone);
                            }
                        } else {
                            addErrorLog(province + "省", "无", phone);
                        }


                    }

                }

            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void addErrorLog(String city, String value, String phone) {
        GlobalConfig globalConfig = new GlobalConfig();
        globalConfig.setGlobalKey(city);
        globalConfig.setGlobalValue(value);
        globalConfig.setChannel(phone);
        globalConfigDao.insert(globalConfig);
    }


    /**
     * 检测城市是否存在，并且匹配code
     */
    @Override
    @Async
    public void check(int idBegin, int idEnd) {
        Map<String, Object> param = new HashMap<>();
        param.put("idBegin", idBegin);
        param.put("idEnd", idEnd);
        try {
            List<Map<String, Object>> phoneList = getList(param);
            if (phoneList != null && phoneList.size() > 0) {
                for (Map<String, Object> map : phoneList) {
                    if (map != null) {
                        //先检查省份，再检查城市
                        String province = (String) map.get("province");
                        String provinceCode = (String) map.get("provinceCode");
                        String phone = (String) map.get("phone");

                        Map<String, Object> provinceParam = new HashMap<>();
                        provinceParam.put("shortName", province);
                        provinceParam.put("code", provinceCode);
                        provinceParam.put("levelType", 1);
                        List<Map<String, Object>> provinceList = lmCmsAreasDao.getByPage(provinceParam);
                        if (provinceList != null && provinceList.size() > 0) {
                            if (provinceList.size() == 1) {
                                Map<String, Object> provinceArea = provinceList.get(0);

                                String city = (String) map.get("city");
                                String cityCode = (String) map.get("areaCode");

                                Map<String, Object> cityParam = new HashMap<>();
                                cityParam.put("shortName", city);
                                cityParam.put("code", cityCode);
                                cityParam.put("levelType", 2);
                                cityParam.put("parentCode", provinceArea.get("code"));
                                List<Map<String, Object>> cityList = lmCmsAreasDao.getByPage(cityParam);
                                if (cityList != null && cityList.size() > 0) {
                                    if (cityList.size() == 1) {
                                        Map<String, Object> cityArea = cityList.get(0);
                                        addCity(provinceArea.get("name").toString(),
                                                provinceArea.get("code").toString(),
                                                cityArea.get("name").toString(),
                                                cityArea.get("code").toString());
                                    } else {
                                        addErrorLog(city, "多个城市", null);
                                    }
                                } else {
                                    Map<String, Object> areaParam = new HashMap<>();
                                    areaParam.put("shortName", city);
                                    areaParam.put("code", cityCode);
                                    areaParam.put("levelType", 3);
                                    List<Map<String, Object>> areaList = lmCmsAreasDao.getByPage(areaParam);
                                    if (areaList != null && areaList.size() > 0) {
                                        if (areaList.size() == 1) {
                                            Map<String, Object> lmCmsArea = areaList.get(0);
                                            //在找到它的上级
                                            Map<String, Object> cityParam2 = new HashMap<>();
                                            cityParam2.put("code", lmCmsArea.get("parentCode"));
                                            cityParam2.put("levelType", 2);
                                            List<Map<String, Object>> cityList2 = lmCmsAreasDao.getByPage(cityParam2);
                                            if (areaList != null && areaList.size() > 0) {
                                                if (areaList.size() == 1) {
                                                    addCity(provinceArea.get("name").toString(),
                                                            provinceArea.get("code").toString(),
                                                            lmCmsArea.get("name").toString(),
                                                            lmCmsArea.get("code").toString());
                                                } else {
                                                    addErrorLog(city, "3级城市有多个2级城市", null);
                                                }
                                            } else {
                                                addErrorLog(city, "3级城市无2级", null);
                                            }


                                        } else {
                                            addErrorLog(city, "3级多城市", null);
                                        }
                                    } else {
                                        addErrorLog(city, "无", null);
                                    }

                                }
                            } else {
                                addErrorLog(province + "省", "多个省", null);
                            }
                        } else {
                            addErrorLog(province + "省", "无", null);
                        }


                    }

                }

            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void addCity(String province, String provinceCode, String city, String cityCode) {
        Map<String, Object> param = new HashMap<>();
        param.put("cityCode", cityCode);
        List<Map<String, Object>> mobileList = lmCmsMobileDao.getByPage(param);
        if (mobileList != null && mobileList.size() > 0) {

        } else {
            LmCmsMobile lmCmsMobile = new LmCmsMobile();
            lmCmsMobile.setProvince(province);
            lmCmsMobile.setProvinceCode(provinceCode);
            lmCmsMobile.setCity(city);
            lmCmsMobile.setCityCode(cityCode);
            lmCmsMobileDao.insert(lmCmsMobile);
        }
    }


    /**
     * 终极验证
     */
    @Override
    @Async
    public void supercheck(int idBegin, int idEnd) {
        Map<String, Object> param = new HashMap<>();
        param.put("idBegin", idBegin);
        param.put("idEnd", idEnd);
        try {
            List<Map<String, Object>> phoneList = getList(param);
            if (phoneList != null && phoneList.size() > 0) {
                for (Map<String, Object> map : phoneList) {
                    if (map != null) {
                        //先检查省份，再检查城市
                        String province = (String) map.get("province");
                        String provinceCode = (String) map.get("provinceCode");
                        String city = (String) map.get("city");
                        String cityCode = (String) map.get("areaCode");
                        String phone = (String) map.get("phone");

                        if (StringUtils.isNotBlank(province) &&
                                StringUtils.isNotBlank(provinceCode) &&
                                StringUtils.isNotBlank(city) &&
                                StringUtils.isNotBlank(cityCode)) {

                        } else {
                            addErrorLog("省市", "数据缺失", phone);
                        }

                        Map<String, Object> mobileParam = new HashMap<>();
                        mobileParam.put("province", province);
                        mobileParam.put("provinceCode", provinceCode);
                        mobileParam.put("city", city);
                        mobileParam.put("cityCode", cityCode);
                        List<Map<String, Object>> provinceList = lmCmsMobileDao.getByPage(mobileParam);
                        if (provinceList != null && provinceList.size() == 1) {

                        } else {
                            addErrorLog("省市", "多条数据", phone);
                        }


                    }

                }

            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    public void setRedis() {
        try {
            int i = 0;
            List<Map<String, Object>> phoneList = getList(new HashMap<>());
            for (Map<String, Object> phoneMap : phoneList) {
                String phone = phoneMap.get("phone").toString();
                Mobilehd mobilehd = new Mobilehd();
                mobilehd.setCity(phoneMap.get("city").toString());
                mobilehd.setCityCode(phoneMap.get("cityCode").toString());
                mobilehd.setProvince(phoneMap.get("province").toString());
                mobilehd.setProvinceCode(phoneMap.get("provinceCode").toString());
                String phoneJson = JSON.toJSONString(mobilehd);
                redisClient.set("mobilehd" + phone, phoneJson);
                System.out.println(i++);
            }


        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    public Result getMobilehd(String mobile) throws Exception {
        Result result = new Result();
        if (mobile.length() < 7) {
            result.setCode(StatusCode.MOBILE_HD_FORMAT_ERROR);
            result.setMsg(StatusCode.codeMsgMap.get(StatusCode.MOBILE_FORMAT_ERROR));
            return result;
        }
        result.setCode(StatusCode.OK);
        result.setMsg(StatusCode.codeMsgMap.get(StatusCode.OK));
        String hd = mobile.substring(0, 7);
        Mobilehd mobilehd = new Mobilehd();
        /*先从redis中获取归属地信息，redis中没有，再从数据库获取,数据库中没有，再从api获取*/
        String json = redisClient.get("mobilehd" + hd);
        if (StringUtils.isNotBlank(json)) {
            mobilehd = JSON.parseObject(json, Mobilehd.class);
            result.setData(mobilehd);
        } else {
            Map<String, Object> param = new HashMap<>();
            param.put("phone", hd);
            List<Map<String, Object>> phoneList = getList(param);
            if (phoneList != null && phoneList.size() > 0) {
                for (Map<String, Object> phoneMap : phoneList) {
                    mobilehd.setCity(phoneMap.get("city").toString());
                    mobilehd.setCityCode(phoneMap.get("cityCode").toString());
                    mobilehd.setProvince(phoneMap.get("province").toString());
                    mobilehd.setProvinceCode(phoneMap.get("provinceCode").toString());
                    result.setData(mobilehd);
                }
            } else {
                //调用api
                String rejson = MobileUtil.mobile(mobile);
                JSONObject jsonObject = JSON.parseObject(rejson);
                logger.error(jsonObject.toString());
                if (jsonObject != null) {
                    Integer ret = jsonObject.getInteger("ret");
                    if (!NumberUtil.isNullOrZero(ret)) {
                        if (ret.intValue() == 200) {
                            JSONObject data = jsonObject.getJSONObject("data");
                            String city = data.getString("city");
                            String cityCode = data.getString("area_code");
                            String province = data.getString("prov");
                            Map<String, Object> provinceParam = new HashMap<>();
                            provinceParam.put("shortName", province);
                            provinceParam.put("levelType", 1);
                            List<Map<String, Object>> provinceList = lmCmsAreasDao.getByPage(provinceParam);
                            if (provinceList != null && provinceList.size() > 0) {
                                if (provinceList.size() == 1) {
                                    Map<String, Object> provinceArea = provinceList.get(0);
                                    String provinceCode = (String) provinceArea.get("code");
                                    mobilehd.setCity(city);
                                    mobilehd.setCityCode(cityCode);
                                    mobilehd.setProvince(province);
                                    mobilehd.setProvinceCode(provinceCode);
                                    /*存储到redis*/
                                    String phoneJson = JSON.toJSONString(mobilehd);
                                    redisClient.set("mobilehd" + hd, phoneJson);
                                    /*存储到数据库*/
                                    LmCmsPhone lmCmsPhone = new LmCmsPhone();
                                    lmCmsPhone.setPref(mobile.substring(0, 3));
                                    lmCmsPhone.setPhone(hd);
                                    lmCmsPhone.setProvince(province);
                                    lmCmsPhone.setCity(city);
                                    lmCmsPhone.setIsp(data.getString("isp"));
                                    lmCmsPhone.setPostCode(data.getString("zip_code"));
                                    lmCmsPhone.setCityCode(data.getString("city_code"));
                                    lmCmsPhone.setAreaCode(data.getString("area_code"));
                                    lmCmsPhone.setProvinceCode(provinceCode);
                                    insert(lmCmsPhone);
                                }
                            }
                            result.setData(mobilehd);
                        } else if (ret.intValue() == 40001) {
                            result.setCode(StatusCode.MOBILE_HD_FORMAT_ERROR);
                            result.setMsg(StatusCode.codeMsgMap.get(StatusCode.MOBILE_FORMAT_ERROR));
                        } else if (ret.intValue() == 40002) {
                            result.setCode(StatusCode.MOBILE_HD_NOT_EXIST);
                            result.setMsg(StatusCode.codeMsgMap.get(StatusCode.MOBILE_HD_NOT_EXIST));
                        }
                    }

                }
            }
        }

        return result;
    }


}
